﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MyBlog.IService;
using MyBlog.JWT.Utility._MD5;
using MyBlog.JWT.Utility.ApiResult;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyBlog.JWT.Controllers
{
   /*
    JWT 控制器
    */
  [Route("api/[controller]")]
  [ApiController]
  public class AuthoizeController : ControllerBase
  {
        #region 固定注入 
        private readonly IWriterInfoService _iWriterInfoService;
        public AuthoizeController(IWriterInfoService iWriterInfoService)
        {
            _iWriterInfoService = iWriterInfoService;
        }
        #endregion

        /// <summary>
        /// 登录 JWT授权
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userpwd"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<ApiResult> Login(string username, string userpwd)
        {
            //登录时MD5加密转换
            string pwd = MD5Helper.MD5Encrypt32(userpwd);

            //数据校验
            var writer = await _iWriterInfoService.FindAsync(c => c.UserName == username && c.UserPwd == pwd);
           
            //登录授权判断
            if (writer != null)//登录成功
            {
                /*
                 JWT = HEADER 算法部分 + PAYLOAD 用户信息部分 + VERIFY SIGNATURE 数字签名部分
                 */

                var claims = new Claim[] //用户信息部分 组成JWT信息 不能放敏感信息 
                {
                    new Claim(ClaimTypes.Name, writer.Name),
                    new Claim("Id", writer.Id.ToString()),
                    new Claim("UserName", writer.UserName)
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")); // 数字签名信息部分
                
                // 创建token
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:6060", //issuer代表颁发Token的Web应用程序 【MyBlog.JWT】
                    audience: "http://localhost:5000", //audience是Token的受理者 【MyBlog.Api】
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),//一个小时后过期
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)//加密后返回
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken); //返回最终Token
            }
            else
            {
                //登录失败
                return ApiResultHelper.Error("账号或密码错误");
            }
        }
    }
}
